import express from 'express';

const multer = require('multer');
const path = require('path');

// 文件存储配置;
const storage = multer.diskStorage({
  //路径配置
  destination: function (req, file, cb) {
    cb(null, path.resolve(__dirname, '../../public/upload'));
  },
  //文件名配置
  filename: function (req, file, cb) {
    //4位随机字符+文件名
    const ramdomStr = Math.random().toString(36).slice(-6);
    const ext = path.extname(file.originalname);
    const filename = `${ramdomStr}${ext}`;
    cb(null, filename);
  },
});

// 文件上传配置
const upload = multer({
  storage,
  limits: {
    fileSize: 150 * 1024,
  },
});

const router = express.Router();
router.post('/upload', upload.single('file'), (req: any, res) => {
  console.log(req.query, 'fileQuery');
  const url = `/upload/${req.file.filename}`;
  res.send({
    code: 0,
    msg: '',
    data: url,
  });
});
module.exports = router;
